package server;

import servlet.HttpServlet;
import servlet.Request;
import servlet.Response;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.Map;

public class RequestProcessor extends Thread {
    private Socket socket;
    private Map<String, HttpServlet> servletMap;
    private String appsBase;

    public RequestProcessor(Socket socket, Map<String, HttpServlet> servletMap, String appsBase) {
        this.socket = socket;
        this.servletMap = servletMap;
        this.appsBase = appsBase;
    }

    @Override
    public void run() {
        InputStream inputStream = null;
        try {
            inputStream = socket.getInputStream();

            //封装Request和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());
            //静态资源处理
            if (servletMap.get(request.getUrl()) == null)
                response.outputHtml(appsBase + request.getUrl());
            else {
                try {
                    HttpServlet httpServlet = servletMap.get(request.getUrl());
                    httpServlet.service(request, response);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
